package top.littlejiang.onlinexam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import top.littlejiang.onlinexam.common.base.BasePage;
import top.littlejiang.onlinexam.common.base.BaseServiceImpl;
import top.littlejiang.onlinexam.common.base.BusinessException;
import top.littlejiang.onlinexam.common.base.Constant;
import top.littlejiang.onlinexam.common.utils.DateUtils;
import top.littlejiang.onlinexam.common.utils.JWTUtils;
import top.littlejiang.onlinexam.entity.OlexamClass;
import top.littlejiang.onlinexam.entity.OlexamCourse;
import top.littlejiang.onlinexam.entity.OlexamUserCourse;
import top.littlejiang.onlinexam.mapper.OlexamCourseMapper;
import top.littlejiang.onlinexam.service.OlexamCourseService;
import top.littlejiang.onlinexam.service.OlexamUserCourseService;
import top.littlejiang.onlinexam.service.OlexamUserService;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程表 服务实现类
 * </p>
 *
 * @author chen
 * @since 2021-03-11
 */
@Service
public class OlexamCourseServiceImpl extends BaseServiceImpl<OlexamCourseMapper, OlexamCourse> implements OlexamCourseService {

    @Autowired
    OlexamCourseMapper courseMapper;
    @Autowired
    OlexamUserService userService;
    @Autowired
    OlexamUserCourseService userCourseService;

    /**
     * 分页查询
     *
     * @param page
     * @return
     */
    @Override
    public IPage<OlexamCourse> getCourseListPage(BasePage<OlexamCourse> page) {
        OlexamCourse query = page.getQueryParam();
        QueryWrapper<OlexamCourse> wrapper = new QueryWrapper<>();
        wrapper.eq("a.is_del", 0);
        if (!StringUtils.isBlank(query.getCourseName())) {
            wrapper.like("course_name", query.getCourseName());
        }
        if (page.getPageSize() <= 0) {
            page.setPageSize(10);
        }
        Page<OlexamCourse> p = new Page<>(page.getPageIndex(), page.getPageSize());
        IPage<OlexamCourse> pages = courseMapper.getClassList(p, wrapper);
        return pages;
    }

    /**
     * 更新或新增数据
     *
     * @param course
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void insertOrUpdate(OlexamCourse course) {
        Integer teacheId = userService.checkByName(course.getTeacherName(), course.getTeacherPhone());
        course.setTeacherId(teacheId)
                .setUpdateTime(DateUtils.getTime())
                .setCreateUser(JWTUtils.getUserId());
        if (!Objects.isNull(course.getId()) && !course.getId().toString().equals(Constant.NO_DEL)) {
            OlexamCourse oldCourse = getById(course.getId());
            List<Serializable> oldUsers = userService.getUserIdByClass(oldCourse.getFkClassId());
            userCourseService.deleteByUser(oldUsers);
        }

        saveOrUpdate(course);

        List<OlexamUserCourse> userCourses = new ArrayList<>();
        List<Serializable> newUsers = userService.getUserIdByClass(course.getFkClassId());
        if (!CollectionUtils.isEmpty(newUsers)){
            newUsers.stream().forEach(item -> {
                OlexamUserCourse temp = new OlexamUserCourse();
                temp.setFkUserId((Integer) item);
                temp.setFkCourseId(course.getId());
                userCourses.add(temp);
            });
            userCourseService.saveBatch(userCourses, userCourses.size());
        }

    }

    /**
     * 根据授课老师id，查询所有课程
     *
     * @param userId
     * @return
     */
    @Override
    public List<String> selectByteacher(Integer userId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.select("distinct course_name");
        wrapper.eq("teacher_id", userId);
        wrapper.eq("is_del", 0);
        List<String> list = this.listObjs(wrapper);
        return list;
    }

    /**
     * 根据授课老师id，课程名(可只传其中一个参数)，查询所有课程id
     *
     * @param userId
     * @param courseName
     * @return
     */
    @Override
    public List<Integer> selectIdsByTeacher(Integer userId, String courseName) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.select("id");
        if (!Objects.isNull(userId)) {
            wrapper.eq("teacher_id", userId);
        }
        if (StringUtils.isNoneBlank(courseName)) {
            wrapper.eq("course_name", courseName);
        }
        wrapper.eq("is_del", 0);
        List<Integer> list = this.listObjs(wrapper);
        return list;
    }

    /**
     * 根据用户id，课程名，查询所有课程id
     * 用户id =》 user表的fk_class_id --> course_id
     *
     * @param userId
     * @param courseName
     * @return
     */
    @Override
    public List<Serializable> selectIdsByUser(Integer userId, String courseName) {
        List<Serializable> list = userCourseService.selectIdsByUser(userId, courseName);
        return list;
    }

    /**
     * 根据用户id 查找去重后的课程名
     *
     * @param userId
     * @return
     */
    @Override
    public List<String> selectByUser(Integer userId) {
        List<Serializable> ids = userCourseService.selectIdsByUser(userId, null);
        List<OlexamCourse> courses = this.listByIds(ids);
        return courses.stream().map(OlexamCourse::getCourseName).collect(Collectors.toList());
    }

    /**
     * 根据课程名查找对应班级
     *
     * @param courseName
     * @return
     */
    @Override
    public List<OlexamClass> getClassByCourse(String courseName) {
        if (StringUtils.isBlank(courseName)) {
            throw new BusinessException("请输入课程名");
        }
        return baseMapper.getClassByCourse(courseName);
    }

    /**
     * 根据课程名,班级查找id
     *
     * @param classId
     * @param courseName
     * @return
     */
    @Override
    public List<Serializable> getIdsByClass(Integer classId, String courseName) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.select("id");
        if (StringUtils.isNotBlank(courseName)) {
            wrapper.eq("course_name", courseName);
        }
        if (!Objects.isNull(classId)) {
            wrapper.eq("fk_class_id", classId);
        }
        List<Serializable> list = this.listObjs(wrapper);
        return list;
    }

    /**
     * 删除课程及用户课程对应关系
     *
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void delete(List<Serializable> ids) {
        logicDeleteById(ids);
        userCourseService.deleteByCourse(ids);
    }


}
